﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VSA.Applications.VSA.WebService;

namespace VSA.Applications
{
    public partial class CompanyInfoForm : Form
    {
        #region Properties and variable values
        private CompanyListForm listForm;
        private SearchGuideForm guideForm;
        private InfoEditGuideForm guide2AddForm;
        private Boolean UpdateEnable { get; set; }
        MainService _CompanyService = WebServiceFactory.GetService();
        MainService _CompanyProjectService = WebServiceFactory.GetService();
        MainService _ProjectService = WebServiceFactory.GetService();
        MainService _CompanyPersonService = WebServiceFactory.GetService();
        MainService _PersonService = WebServiceFactory.GetService();
        MainService _ContactPersonService = WebServiceFactory.GetService();
        MainService _ActivityService = WebServiceFactory.GetService();
        int _CompanyId = int.MinValue;
        bool _IsUpdated = false;
        public string ActivityList
        {
            get
            {
                return this.cb_Activity.Text;
            }

            set
            {
                this.cb_Activity.Text = value;
            }
        }
        #endregion

        public CompanyInfoForm(CompanyListForm listForm)
        {
            InitializeComponent();
            Initialize();
            this.listForm = listForm;
            this.UpdateEnable = false;
        }

        public CompanyInfoForm(InfoEditGuideForm guideForm, int companyId)
        {
            InitializeComponent();
            _CompanyId = companyId;
            Initialize();
            this.guide2AddForm = guideForm;
        }

        public CompanyInfoForm(SearchGuideForm guideForm, int companyId)
        {
            InitializeComponent();
            _CompanyId = companyId;
            Initialize();
            this.guideForm = guideForm;
        }

        public CompanyInfoForm(CompanyListForm listForm, int companyId)
        {
            InitializeComponent();
            _CompanyId = companyId;
            Initialize();
            this.listForm = listForm;
        }

        void Initialize()
        {
            
            #region aync_process
            _CompanyService.UpdateCompanyCompleted += new UpdateCompanyCompletedEventHandler(UpdateCompanyCompleted);
            _CompanyService.AddCompanyCompleted += new AddCompanyCompletedEventHandler(AddCompanyCompleted);
            _CompanyService.DeleteCompanyCompleted += new DeleteCompanyCompletedEventHandler(DeleteCompanyCompleted);
            #endregion aync_process

            GetCompanyData();
            this.btn_Delete.Enabled = false;
        }

        private void GetCompanyData()
        {
            Company company = _CompanyService.GetCompanyModel(_CompanyId);
            BindProjectCheckBox(company.ReferenceProjectList, company.CompanyProject);
            BindActivityList(company.ReferenceActivityList);
            ShowProcess(false);
            SwitchButtons(false);

            if (_CompanyId != int.MinValue )
            {
                txt_CompanyName.Text = company.CompanyName;
                txt_AddressStreet.Text = company.Street;
                txt_City.Text = company.City;
                txt_Country.Text = company.Country;
                txt_Conteinet.Text = company.Continent;
                txt_Website.Text = company.Website;
                txt_Comments.Text = company.Comments;
                txt_Email.Text = company.Email;
                if (string.IsNullOrEmpty((company.Email + "").Trim()))
                    btnEmail.Hide();

                txt_Historic.Text = company.Historic;
                if (string.IsNullOrEmpty((company.Telephone1 + "").Trim()))
                    btnSkype1.Hide();
                txt_Phone1.Text = company.Telephone1;
                if (string.IsNullOrEmpty((company.TelePhone2 + "").Trim()))
                    btnSkype2.Hide();
                txt_Phone2.Text = company.TelePhone2;
                txt_PostCode.Text = company.PostCode;
                cb_Activity.Text = company.Activity;
                lbl_CreateBy.Text = company.CreateBy;
                lbl_CreateDate.Text = company.CreateDate == DateTime.MinValue ? "" : company.CreateDate.ToString();
                lbl_UpdateBy.Text = company.UpdateBy;
                lbl_UpdateDate.Text = company.LatestUpdate.ToString();
                BindContactPersonCheckBox(company.ReferenceContactPersonList, company.CompanyPerson);
                EnableController(false);
            }
            else
            {
                this.btnSkype1.Visible = false;
                this.btnSkype2.Visible = false;
                this.btnEmail.Visible = false;
                EnableController(true);
            }
        }

        void SwitchButtons(bool isEnable)
        {
            this.btn_Submit.Enabled = this.btn_New.Enabled = true;
            if (_CompanyId != int.MinValue)
            {
                this.btn_Delete.Enabled = isEnable;
            }
            else
            {
                this.btn_Submit.Image = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "\\Resources\\save.png");
            }
            
        }

        void SwitchAllButtons(bool isEnable)
        {
            this.btn_Delete.Enabled = this.btn_New.Enabled = this.btn_Submit.Enabled = isEnable;
        }

        void ClearServices()
        {
            _CompanyService = null;
            _CompanyProjectService = null;
            _ProjectService = null;
            _CompanyPersonService = null;
            _PersonService = null;
            _ContactPersonService = null;
            _ActivityService = null;
        }

        private void CompanyInfoForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            CloseSelf(false);
        }

        private void CloseSelf(bool isCustomized)
        {
            if (listForm != null)
            {
                listForm.Show();
                listForm.TopMost = true;
            }
            else if (guideForm != null)
            {
                guideForm.Show();
                guideForm.TopMost = true;
            }
            else if (this.guide2AddForm != null)
            {
                guide2AddForm.Show();
                guide2AddForm.TopMost = true;
            }

            this.Dispose();
            if (_IsUpdated && listForm != null && isCustomized)
            {
                listForm.RefreshData();
            }
        }

        void GetCompanyModelCompleted(object sender, GetCompanyModelCompletedEventArgs e)
        {
            txt_CompanyName.Text = e.Result.CompanyName;
            txt_AddressStreet.Text = e.Result.Street;
            txt_City.Text = e.Result.City;
            txt_Country.Text = e.Result.Country;
            txt_Conteinet.Text = e.Result.Continent;
            txt_Website.Text = e.Result.Website;
            txt_Comments.Text = e.Result.Comments;
            txt_Email.Text = e.Result.Email;
            txt_Historic.Text = e.Result.Historic;
            txt_Phone1.Text = e.Result.Telephone1;
            txt_Phone2.Text = e.Result.TelePhone2;
            txt_PostCode.Text = e.Result.PostCode;
            cb_Activity.Text = e.Result.Activity;
            lbl_CreateBy.Text = e.Result.CreateBy;
            lbl_CreateDate.Text = e.Result.CreateDate.ToString();
            lbl_UpdateBy.Text = e.Result.UpdateBy;
            lbl_UpdateDate.Text = e.Result.LatestUpdate.ToString();
            BindProjectCheckBox(e.Result.ReferenceProjectList, e.Result.CompanyProject);
            BindContactPersonCheckBox(e.Result.ReferenceContactPersonList, e.Result.CompanyPerson);
            BindActivityList(e.Result.ReferenceActivityList);
            ShowProcess(true);
        }

        void BindActivityList(Activity[] list)
        {
            string tmpActivity = cb_Activity.Text;
            cb_Activity.DataSource = list;
            cb_Activity.DisplayMember = "ActivityContent";
            cb_Activity.ValueMember = "Did";
            cb_Activity.Text = tmpActivity;
        }

        public void BuildActivityBox(DataTable dt)
        {
            if (this.cb_Activity.Items.Count > 0)
            {
                this.cb_Activity.DataSource = null;
                this.cb_Activity.Items.Clear();
            }

            this.cb_Activity.DataSource = dt;
            this.cb_Activity.ValueMember = "ActivityContent";
            this.cb_Activity.DisplayMember = "ActivityContent";
        }

        void BindProjectCheckBox(Project[] list, CompanyProjectMapping[] projectMappingList)
        {
            int top = 0;
            foreach (Project project in list)
            {
                CheckBox newck = new CheckBox();
                newck.Font = new Font("Calibri", 12);
                newck.Tag = project.ProjectId;
                newck.Text = project.ProjectName;
                newck.Top = top;
                pl_Projects.Controls.Add(newck);
                top += 20;
                foreach (CompanyProjectMapping projectMapping in projectMappingList)
                {
                    if (newck.Tag.ToString() == projectMapping.ProjectId.ToString())
                    {
                        newck.Checked = true;
                    }
                }
            }
        }

        void BindContactPersonCheckBox(ContactPerson[] list, CompanyPersonMapping[] contactPersonMappingList)
        {
            int top = 0;
            foreach (ContactPerson contactPerson in list)
            {
                
                foreach (CompanyPersonMapping contactPersonMapping in contactPersonMappingList)
                {
                    if (contactPerson.PersonId == contactPersonMapping.PersonId)
                    {
                        Label newlb = new Label();
                        newlb.Font = new Font("Calibri", 12);
                        newlb.Tag = contactPerson.PersonId;
                        newlb.Top = top;
                        pl_ContactPerson.Controls.Add(newlb);
                        top += 20;
                        newlb.Text = contactPerson.GivenName + " " + contactPerson.FamilyName;
                    }
                }
            }
            if (contactPersonMappingList.Length == 0)
                pl_ContactPerson.Controls.Clear();
        }

        #region Async Event handler

        void UpdateCompanyCompleted(object sender, AsyncCompletedEventArgs e)
        {
            AddCompanyProjectMapping();
            MessageBox.Show(
                "Update successfully",
                "System Information",
                MessageBoxButtons.OK,
                MessageBoxIcon.Information
            );
            ShowProcess(true);
            if (e.Error == null)
            {
                if (listForm != null)
                {
                    _IsUpdated = true;
                }
            }
            
        }

        void AddCompanyCompleted(object sender, AsyncCompletedEventArgs e)
        {
            _CompanyId = (e as AddCompanyCompletedEventArgs).Result;
            AddCompanyProjectMapping();
            MessageBox.Show(
                "Add new successfully",
                "System Information",
                MessageBoxButtons.OK,
                MessageBoxIcon.Information
            );
            ShowProcess(true);
        }

        void AddCompanyProjectMapping()
        {
            List<int> addingList = new List<int>();
            List<int> deleteingList = new List<int>();
            foreach (CheckBox cb in pl_Projects.Controls)
            {
                if(cb.Checked)
                    addingList.Add(int.Parse(cb.Tag.ToString()));
                else
                    deleteingList.Add(int.Parse(cb.Tag.ToString()));
            }
            _CompanyProjectService.BatchAddCompanyProjectMappingAsync(_CompanyId, addingList.ToArray(), deleteingList.ToArray());
        }

        void DeleteCompanyCompleted(object sender, AsyncCompletedEventArgs e)
        {
            _IsUpdated = true;
            MessageBox.Show(
                "Delete successfully",
                "System Information",
                MessageBoxButtons.OK,
                MessageBoxIcon.Information
            );
            ShowProcess(true);
            MessageBox.Show("Current info was deleted, and this window will be closed.");
            CloseSelf(true);
            this.Dispose();
        }

        #endregion

        private void SaveCompany()
        {
            ShowProcess(false);
            
            Company companyModel = new Company();
            companyModel.CompanyId = _CompanyId;
            companyModel.Street = txt_AddressStreet.Text.Trim();
            companyModel.City = txt_City.Text.Trim();
            companyModel.Country = txt_Country.Text.Trim();
            companyModel.Continent = txt_Conteinet.Text.Trim();
            companyModel.CompanyName = txt_CompanyName.Text.Trim();
            companyModel.Website = txt_Website.Text.Trim();
            companyModel.Comments = txt_Comments.Text;
            companyModel.Email = txt_Email.Text;
            companyModel.Historic = txt_Historic.Text;
            companyModel.Telephone1 = txt_Phone1.Text;
            companyModel.TelePhone2 = txt_Phone2.Text;
            companyModel.PostCode = txt_PostCode.Text;
            companyModel.Activity = cb_Activity.Text;
            companyModel.LatestUpdate = DateTime.Now;
            companyModel.UpdateBy = OfficeHelper.GetName();
            _ActivityService.BatchAddActivity(cb_Activity.Text.Split(','));

            companyModel.Activity = cb_Activity.Text;

            if (_CompanyId != int.MinValue)
            {
                _CompanyService.UpdateCompanyAsync(companyModel);
            }
            else
            {
                if (String.IsNullOrEmpty(txt_CompanyName.Text.Trim()))
                {
                    this.errorProvider1.SetError(txt_CompanyName, "Please Input Direct Telephone");
                    return;
                }
                companyModel.CreateBy = OfficeHelper.GetName();
                companyModel.CreateDate = DateTime.Now;
                _CompanyService.AddCompanyAsync(companyModel);
            }
        }

        private void EnableController(Boolean controlStatus)
        {
            this.txt_CompanyName.ReadOnly = !controlStatus;
            this.txt_Phone1.ReadOnly = !controlStatus;
            this.txt_Phone2.ReadOnly = !controlStatus;
            this.txt_Email.ReadOnly = !controlStatus;
            this.txt_AddressStreet.ReadOnly = !controlStatus;
            this.txt_Country.ReadOnly = !controlStatus;
            this.txt_City.ReadOnly = !controlStatus;
            this.txt_PostCode.ReadOnly = !controlStatus;
            this.txt_Conteinet.ReadOnly = !controlStatus;
            this.txt_Website.ReadOnly = !controlStatus;
            this.cb_Activity.Enabled = controlStatus;
            this.txt_Historic.ReadOnly = !controlStatus;
            this.txt_Comments.ReadOnly = !controlStatus;
            this.pl_Projects.Enabled = controlStatus;
            this.pl_ContactPerson.Enabled = controlStatus;
            this.btn_Delete.Enabled = controlStatus;
        }

        private void btn_SubmitAdd_Click(object sender, EventArgs e)
        {
            if (this.UpdateEnable)
            {
                SaveCompany();
                this.UpdateEnable = false;
                this.btn_Delete.Enabled = false;
                this.btn_Submit.Image = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "\\Resources\\update.png");
                EnableController(false);
            }
            else
            {
                this.btn_Submit.Image = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "\\Resources\\save.png");
                SwitchButtons(true);
                EnableController(true);
                this.UpdateEnable = true;
                this.btn_Delete.Enabled = true;
            }
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            CloseSelf(true);
        }

        private void btn_Delete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure delete this record?", "Confirm to exit", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
            {
                ShowProcess(false);
                _CompanyService.DeleteCompanyAsync(_CompanyId);
            }
        }

        private void btnSkype1_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txt_Phone1.Text.Trim()))
            {
                Utility.ShellExecute(0, String.Empty, "skype:" + txt_Phone1.Text.Trim() + "?call", String.Empty, String.Empty, 1);
            }
        }

        private void btnSkype2_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txt_Phone1.Text.Trim()))
            {
                Utility.ShellExecute(0, String.Empty, "skype:" + txt_Phone2.Text.Trim() + "?call", String.Empty, String.Empty, 1);
            }
        }

        private void btnEmail_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txt_Email.Text.Trim()))
            {
                Utility.ShellExecute(0, String.Empty, "mailto:" + txt_Email.Text.Trim(), String.Empty, String.Empty, 1);
            }
        }

        private void txt_Phone1_Validating(object sender, CancelEventArgs e)
        {

        }

        private void txt_Phone1_Validated(object sender, EventArgs e)
        {
            TextBox txtBox = (TextBox)sender;
            this.errorProvider1.SetError(txtBox, "");
        }

        private void txt_Email_Validated(object sender, EventArgs e)
        {
            TextBox txtBox = (TextBox)sender;
            this.errorProvider1.SetError(txtBox, "");
        }

        private void txt_Email_Validating(object sender, CancelEventArgs e)
        {

        }

        private void lbl_ManageActivity_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ActivityInfoForm activity = new ActivityInfoForm();
            activity.CompanyForm = this;
            activity.ShowDialog(this);
        }

        private void lbl_InsertActivity_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            SelectActivityList selectActivity = new SelectActivityList();
            selectActivity.Owner = this;
            selectActivity.ShowDialog(this);
        }

        private void txt_Phone2_Validating(object sender, CancelEventArgs e)
        {

        }

        private void txt_Phone2_Validated(object sender, EventArgs e)
        {

        }

        private void txt_CompanyName_Validated(object sender, EventArgs e)
        {
            TextBox txtBox = (TextBox)sender;
            this.errorProvider1.SetError(txtBox, "");
        }

        private void txt_CompanyName_Validating(object sender, CancelEventArgs e)
        {
            string errorMsg = string.Empty;
            TextBox txtBox = (TextBox)sender;
            if (string.IsNullOrEmpty(txt_CompanyName.Text))
            {
                e.Cancel = true;
                txtBox.Select(0, txtBox.Text.Length);
                this.errorProvider1.SetError(txt_CompanyName, "Please input company name.");
            }
        }

        void ShowProcess(bool isEnd)
        {
            if (!isEnd)
            {
                SwitchAllButtons(false);
            }
            else
            {
                SwitchAllButtons(true);
            }
        }

        private void btn_New_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Do you want to create new record? \r\nall fields will be cleared.", "Confirm to exit", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
            {
                _CompanyId = int.MinValue;
                this.txt_CompanyName.Text = String.Empty;
                this.txt_Phone1.Text = String.Empty;
                this.txt_Phone2.Text = String.Empty;
                this.txt_Email.Text = String.Empty;
                this.txt_AddressStreet.Text = String.Empty;
                this.txt_Country.Text = String.Empty;
                this.txt_City.Text = String.Empty;
                this.txt_PostCode.Text = String.Empty;
                this.txt_Conteinet.Text = String.Empty;
                this.txt_Historic.Text = String.Empty;
                this.txt_Comments.Text = String.Empty;
                this.txt_Website.Text = String.Empty;
                this.cb_Activity.SelectedIndex = 0;
                foreach (Control o in this.pl_Projects.Controls)
                {
                    CheckBox ck = (CheckBox)o;
                    ck.Checked = false;
                }
                pl_ContactPerson.Controls.Clear();
                this.lbl_CreateBy.Text = String.Empty;
                this.lbl_CreateDate.Text = String.Empty;
                this.lbl_UpdateBy.Text = String.Empty;
                this.lbl_UpdateDate.Text = String.Empty;
                this.btn_Delete.Enabled = false;
                this.btnSkype1.Visible = false;
                this.btnSkype2.Visible = false;
                this.btnEmail.Visible = false;
                EnableController(true);
            }
        }
    }
}
